<template>
  <el-container class="admin-layout">
    <el-main>
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>用户管理</span>
            <el-button type="primary" @click="handleOpenDialog()">添加用户</el-button>
          </div>
        </template>

        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="按昵称或手机号搜索"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <el-table :data="filteredUsers" v-loading="loading" style="width: 100%" row-key="id" @expand-change="handleExpand">
          <el-table-column type="expand">
            <template #default="props">
              <el-table v-loading="ordersLoadingMap[props.row.id]" :data="ordersMap[props.row.id] || []" style="width: 100%" size="small">
                <el-table-column prop="id" label="订单ID" width="90" />
                <el-table-column prop="customerId" label="顾客ID" width="80" />
                <el-table-column prop="productId" label="商品ID" width="80" />
                <el-table-column label="商品名称" min-width="140">
                  <template #default="scope">
                    {{ productNameMap[scope.row.productId] || '加载中...' }}
                  </template>
                </el-table-column>
                <el-table-column prop="addressId" label="地址ID" width="90" />
                <el-table-column prop="totalAmount" label="总金额" width="100">
                  <template #default="scope">
                    ¥{{ scope.row.totalAmount.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 'end' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="orderDate" label="下单日期" width="160" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="昵称" />
          <el-table-column prop="phoneNumber" label="手机号" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleOpenDialog(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除这个用户吗?"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

      </el-card>
    </el-main>
  </el-container>

  <!-- Add/Edit Dialog -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="resetForm">
    <el-form :model="formUser" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item label="用户昵称" prop="name">
        <el-input v-model="formUser.name" />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="formUser.phoneNumber" :disabled="!!editingUserId" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import apiClient from '../../axios/axios';
import { ElMessage, ElIcon } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';

interface User {
  id: number;
  name: string;
  phoneNumber: string;
}

interface Order {
  id: number;
  customerId: number;
  productId: number;
  addressId: number;
  status: string;
  subtotalAmount: number;
  shippingFee: number;
  discountAmount: number;
  totalAmount: number;
  orderDate: string;
}

interface Product { id:number; name:string; }

const allUsers = ref<User[]>([]);
const loading = ref(false);
const searchQuery = ref('');


const filteredUsers = computed(() => {
  if (!searchQuery.value) {
    return allUsers.value;
  }
  return allUsers.value.filter(user =>
    user.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    user.phoneNumber.includes(searchQuery.value)
  );
});

const fetchUsers = async () => {
  loading.value = true;
  try {
    const response = await apiClient.get<User[]>('/user');
    allUsers.value = response.data;
  } catch (error) {
    console.error("Failed to fetch users", error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchUsers();
});

// --- Dialog and Form State ---
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref<FormInstance>();
const editingUserId = ref<number | null>(null);

const initialFormUserState = {
  name: '',
  phoneNumber: '',
};

const formUser = reactive({ ...initialFormUserState });

const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
    phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
});


const resetForm = () => {
  Object.assign(formUser, initialFormUserState);
  editingUserId.value = null;
  formRef.value?.clearValidate();
};

const handleOpenDialog = (user?: User) => {
  if (user) {
    dialogTitle.value = '编辑用户';
    editingUserId.value = user.id;
    Object.assign(formUser, user);
  } else {
    dialogTitle.value = '添加用户';
    resetForm();
  }
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        if (editingUserId.value) {
          // API only supports updating name via phone number
          await apiClient.put(`/user/phone/${formUser.phoneNumber}/name`, { name: formUser.name });
          ElMessage.success('用户更新成功');
        } else {
          await apiClient.post('/user', { name: formUser.name, phoneNumber: formUser.phoneNumber });
          ElMessage.success('用户添加成功');
        }
        dialogVisible.value = false;
        fetchUsers();
      } catch (error) {
        console.error('Failed to save user', error);
        ElMessage.error(editingUserId.value ? '更新用户失败' : '添加用户失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleDelete = async (userId: number) => {
  loading.value = true;
  try {
    await apiClient.delete(`/user/${userId}`);
    ElMessage.success('用户删除成功');
    fetchUsers(); // Refresh the list
  } catch (error) {
    console.error('Failed to delete user', error);
    ElMessage.error('删除用户失败');
  } finally {
    loading.value = false;
  }
};

// --- 用户订单展开逻辑 ---
const ordersMap = ref<Record<number, Order[]>>({});
const ordersLoadingMap = ref<Record<number, boolean>>({});
const productNameMap = ref<Record<number, string>>({});

const handleExpand = async (row: User, expandedRows: User[]) => {
  if (!expandedRows.includes(row)) return; // 仅在展开行时触发
  if (ordersMap.value[row.id]) return; // 已加载过
  ordersLoadingMap.value[row.id] = true;
  try {
    const res = await apiClient.get<Order[]>(`/orders/user/${row.id}`);
    ordersMap.value[row.id] = res.data;

    // 为订单中的商品获取名称
    const missingIds = res.data.map(o => o.productId).filter(id => !productNameMap.value[id]);
    if (missingIds.length) {
      await Promise.all(
        missingIds.map(async id => {
          try {
            const pRes = await apiClient.get<Product>(`/product/${id}`);
            productNameMap.value[id] = pRes.data.name;
          } catch (err) {
            console.error('获取商品名称失败', err);
          }
        })
      );
    }
  } catch (e) {
    ElMessage.error('获取用户订单失败');
    ordersMap.value[row.id] = [];
  } finally {
    ordersLoadingMap.value[row.id] = false;
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.filter-container {
  margin-bottom: 20px;
}
.admin-layout {
  height: 100%;
}
</style>
